package org.siqisource.webstart.core.widgets.messagetip.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.codehaus.jackson.map.ObjectMapper;
import org.siqisource.webstart.core.page.PageConstants;
import org.siqisource.webstart.core.widgets.messagetip.model.MessageTip;

/*
 * 输出web系统的根目录
 */
public class MessageTipTag extends TagSupport {

	public static final ObjectMapper objectMapper = new ObjectMapper();

	public int doStartTag() throws JspTagException {
		Object messageTip = pageContext.findAttribute(PageConstants.MESSAGE_TIP);
		if (messageTip != null && messageTip instanceof MessageTip) {
			JspWriter out = pageContext.getOut();

			try {
				out.print(getScript((MessageTip) messageTip));
			} catch (IOException ex) {
				throw new JspTagException("IOError:" + ex.getMessage());
			}
		}
		return Tag.SKIP_BODY;
	}

	public int doEndTag() throws JspTagException {
		return Tag.EVAL_PAGE;
	}

	public String getScript(MessageTip messageTip) {
		StringBuffer sbScript = new StringBuffer(256);
		try {
			sbScript.append("<script type='text/javascript'>\r\n");
			String jsonString = objectMapper.writeValueAsString(messageTip);
			sbScript.append("window.top.$.omMessageTip.show(");
			sbScript.append(jsonString);
			sbScript.append(");\r\n</script>");
		} catch (Exception e) {
		}
		return sbScript.toString();
	}

}
